package com.shwread.android.ui.page;

import java.util.List;

import logic.constants.Const;
import logic.constants.DefaultConsts;
import logic.util.NetworkUtil;
import logic.util.ScreenUtil;

import org.geometerplus.android.util.QyreaderPerferencesUtil;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import base.tina.core.task.infc.ITaskResult;

import com.netease.nim.demo.contact.cache.ContactDataCache;
import com.netease.nim.demo.contact.cache.TeamDataCache;
import com.netease.nim.demo.contact.model.Buddy;
import com.netease.nim.demo.contact.protocol.ContactHttpClient;
import com.netease.nim.demo.contact.protocol.IContactHttpCallback;
import com.netease.nim.demo.main.activity.ContactMainActivity;
import com.netease.nim.demo.main.reminder.ReminderItem;
import com.netease.nim.demo.main.reminder.ReminderManager;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.shwread.android.qysw.activity.BaseBusinessActivity;
import com.shwread.android.qysw.activity.MainActivity;
import com.shwread.android.qysw.activity.MessageActivity;
import com.shwread.android.qysw.activity.NewInteractionActvListActivity;
import com.shwread.android.qysw.activity.NewInteractionCenterUserPublishActivity;
import com.shwread.android.qysw10000204.R;
import com.shwread.android.ui.dialog.GuideDialog;
import com.shwread.android.ui.widget.IManagerClickPopListener;
import com.shwread.android.ui.widget.ManagerClickPopupWindow;
import com.shwread.android.ui.widget.OldInteractionContentView;
import com.shwread.android.ui.widget.refresh.PullToRefreshScrollView;
import com.shwread.android.ui.widget.refresh.PullToRefreshUtil;
import com.shwread.android.ui.widget.refresh.base.PullToRefreshBase;
import com.shwread.android.ui.widget.refresh.base.PullToRefreshBase.OnRefreshListener;
import com.shwread.httpsdk.http.callback.BaseAction;
import com.shwread.httpsdk.http.face.QryUnReadActivityAction;
import com.shwread.httpsdk.http.face.QryUnReadTotalAction;
import com.shwread.httpsdk.util.NetUtil;
import com.tgx.tina.android.ipc.framework.IUIPage;


/**
 * 新的互动中心页面
 *
 * @author yqq
 * @date 2015年5月6日
 */

public class OldInteractionCenterPage
        extends
        AbstractUIPage<MainActivity>
        implements
        OnClickListener,
        ReminderManager.UnreadNumChangedCallback
{
    private static final String             TAG       = "OldInteractionCenterPage";

    private static OldInteractionCenterPage instance;
    private TextView                        tvTitle;
    private Button                          ivPersion;
    private Button                          ivManager;
    private Button                          ivSetting;
    private ImageView                       ivManagerRedDot;
    private ImageView                       ivPersionRedDot;

    private View                            titleView;
    private PullToRefreshScrollView contentView;

    // added by zouqp
    private LinearLayout                    ll_interaction_contentview;
    private OldInteractionContentView contentItemView;
    private View                            messageLayout;
    private ImageView                       ivMsgUnread;

    private int                             pagetype;                              // 页面类型 0普通用户   1经理   2 为客户
    /** 没有网络0 ，没有主题1 */
    private int                             net_theme = 3;

    private LinearLayout                    nonet_theme_ll;
    private Button                          setnet;
    private ImageView                       no_nettheme_img;
    private TextView                        no_nettheme_tv;
    private AnimationDrawable               postmsgAnimation;

    private RelativeLayout                  rlayNoNetTopTip;

    public static OldInteractionCenterPage getInstance(MainActivity bActivity) {
        if (instance == null)
        {
            instance = new OldInteractionCenterPage(bActivity);
        }
        else
        {
            instance.setActivity(bActivity);
        }
        return instance;
    }

    public OldInteractionCenterPage(MainActivity t) {
        super(t);
    }

    @Override
    public <E extends Activity> View createView(E arg0, int arg1) {
        if (null != curMyView) return curMyView;
        curMyView = bActivity.getLayoutInflater().inflate(R.layout.old_interaction_center_layout, null);
        initView();
        setListener();
        initGuide();
        setPageInfo();

        // observers
        TeamDataCache.getInstance().init();

        prepareCacheData();

        new Handler(bActivity.getMainLooper()).postDelayed(new Runnable()
        {
            @Override
            public void run() {
                prepareRemoteData();
            }
        }, 500);

        //		registerMsgUnreadInfoObserver(true);
        //		registerSystemMessageObservers(true);
        //		requestSystemMessageUnreadCount();
        return curMyView;
    }

    private void prepareCacheData() {
        ContactHttpClient.getInstance().getTokenOnLogin();
        ContactDataCache.getInstance().initBuddyCache(null);
        TeamDataCache.getInstance().initTeamCache();
    }

    private void prepareRemoteData() {
        // request buddies data
        if (!ContactDataCache.getInstance().isBuddyCacheDataEmpty()) { return; }

        ContactHttpClient.getInstance().getAddressBook(new IContactHttpCallback<List<Buddy>>()
        {
            @Override
            public void onSuccess(List<Buddy> buddies) {
                ContactDataCache.getInstance().addOrUpdateBuddies(buddies);
            }

            @Override
            public void onFailed(int code, String errorMsg) {

            }
        });
    }

    @SuppressLint ("UseSparseArrays")
    void initView() {

        rlayNoNetTopTip = (RelativeLayout) curMyView.findViewById(R.id.new_i_no_net_top_tip_rlay);
        tvTitle = (TextView) curMyView.findViewById(R.id.new_common_header_name);
        tvTitle.setText("互动中心");
        // 普通用户的title图片
        ivPersion = (Button) curMyView.findViewById(R.id.new_common_header_persion);
        // 普通用户的消息红点
        ivPersionRedDot = (ImageView) curMyView.findViewById(R.id.new_common_header_persion_red_dot);
        ivPersionRedDot.setVisibility(View.GONE);
        // 经理的title图片
        ivManager = (Button) curMyView.findViewById(R.id.new_common_header_manager);
        // 经理的消息红点
        ivManagerRedDot = (ImageView) curMyView.findViewById(R.id.new_common_header_manager_red_dot);
        ivManagerRedDot.setVisibility(View.GONE);
        // title的设置按钮
        ivSetting = (Button) curMyView.findViewById(R.id.new_common_header_setting);
        // 联系人未读红点
        ivNewMsg = (Button) curMyView.findViewById(R.id.new_common_header_linkman_newmsg);

        // 显示未读消息的layout
        messageLayout = curMyView.findViewById(R.id.new_common_header_msg_layout);
        messageLayout.setVisibility(View.VISIBLE);
        // 未读消息小红点
        ivMsgUnread = (ImageView) curMyView.findViewById(R.id.new_common_header_msg_unread_flag);

        ll_interaction_contentview = (LinearLayout) curMyView.findViewById(R.id.ll_interaction_contentview);
        // 标题栏--做双击回顶部
        titleView = curMyView.findViewById(R.id.new_common_title_layout);
        // 发布主题
        postmsg = (ImageView) curMyView.findViewById(R.id.new_interaction_center_postmsg);
        postmsg.setVisibility(View.VISIBLE);
        no_nettheme_img = (ImageView) curMyView.findViewById(R.id.new_interaction_no_theme_img);
        // 设置网络按钮
        setnet = (Button) curMyView.findViewById(R.id.new_interaction_no_theme_btn_setting);
        // 没网络或没主题的提示文字
        no_nettheme_tv = (TextView) curMyView.findViewById(R.id.new_interaction_no_theme_tv_text);
        contentView = (PullToRefreshScrollView) curMyView.findViewById(R.id.iteraction_center_view);
        nonet_theme_ll = (LinearLayout) curMyView.findViewById(R.id.new_no_theme_ll);
        if (net_theme == 1)
        {// 没主题
            contentView.setVisibility(View.GONE);
            nonet_theme_ll.setVisibility(View.VISIBLE);
            setnet.setVisibility(View.GONE);
            no_nettheme_tv.setText("没有主题哦，立即发布！");
            no_nettheme_img.setBackgroundResource(R.drawable.new_i_no_theme_icon);
            postmsg.setBackgroundResource(R.drawable.new_i_publish);
            postmsgAnimation = (AnimationDrawable) postmsg.getBackground();
            postmsgAnimation.start();
        }
        else if (net_theme == 0)
        {// 没网络
            contentView.setVisibility(View.GONE);
            nonet_theme_ll.setVisibility(View.VISIBLE);
        }

        PullToRefreshUtil.initLabel(context, contentView);

        // 增加内容项视图
        if (Const.UserRole.equals("0"))
        {
            pagetype = 0;// 普通用户
        }
        else if (Const.UserRole.equals("1"))
        {
            pagetype = 1;//客户经理
        }
        else if (Const.UserRole.equals("2"))
        {
            pagetype = 2;//客户
        }
        contentItemView = new OldInteractionContentView(context);
        contentItemView.setFromType(pagetype);
        contentItemView.setBaseActivity(bActivity);
        contentItemView.setInteractionContentViewListener(new OldInteractionContentView.InteractionContentViewListener()
        {
            @Override
            public void OnLoadDataCompleted(int flag) {
                if (flag == 0)
                {
                    // 首次装载
                    contentView.onRefreshComplete();
                }
                else if (flag == 1)
                { // 刷新装载
                    contentView.onRefreshComplete();
                }
                else if (flag == 2)
                {// 装载更多
                    contentView.onRefreshComplete();
                }
            }
        });

        clearPage();
    }

    void setListener() {
        messageLayout.setOnClickListener(this);
        ivPersion.setOnClickListener(this);
        ivManager.setOnClickListener(this);
        ivSetting.setOnClickListener(this);

        titleView.setOnClickListener(this);
        postmsg.setOnClickListener(this);
        rlayNoNetTopTip.setOnClickListener(this);

        contentView.setOnRefreshListener(new OnRefreshListener<ScrollView>()
        {
            @Override
            public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
                if (contentView.isHeaderShown())
                { // 下拉刷新
                    refresh();
                }
                else if (contentView.isFooterShown())
                { // 上拉加载
                    loadMore();
                }
            }
        });
    }

    private void setPageInfo() {
        if (Const.UserRole.equals("2"))
        {
            pagetype = 2;
            ivPersion.setVisibility(View.VISIBLE);
            ivManager.setVisibility(View.GONE);
        }
        else if (Const.UserRole.equals("1"))
        {
            pagetype = 1;
            ivManager.setVisibility(View.VISIBLE);
//            ivPersion.setVisibility(View.GONE);
        }
        else if (Const.UserRole.equals("0"))
        {
            pagetype = 0;
//            ivPersion.setVisibility(View.GONE);
            ivManager.setVisibility(View.GONE);
        }
    }

    /**
     * 如果页面有数据则清空数据 重新加载
     */
    private void clearPage() {
        // if (ll_interaction_contentview != null)
        // {
        // ll_interaction_contentview.removeAllViews();
        // }
        ll_interaction_contentview.addView(contentItemView);
    }

    /** 下拉刷新 */
    private void refresh() {
        // TODO
        if (NetUtil.isNetworkConnected(context))
        {

            contentItemView.getInteractionData(1);
            rlayNoNetTopTip.setVisibility(View.GONE);
        }
        else
        {
            rlayNoNetTopTip.setVisibility(View.VISIBLE);
            contentView.onRefreshComplete();
        }
    }

    /** 加载更多 */
    private void loadMore() {
        if (!NetUtil.isNetworkConnected(context))
        {

            rlayNoNetTopTip.setVisibility(View.VISIBLE);
        }
        else
        {
            rlayNoNetTopTip.setVisibility(View.GONE);

            if (contentItemView.getDataSize() == 0)
            {
                PullToRefreshUtil.setLoadLabel(contentView, "没有更多了");
            }
            else
            {
                if (contentItemView.getHasMore())
                {
                    // 加载下一页
                    contentItemView.getNextPage();
                    return;
                }
                else if (contentItemView.isGotMaxSize())
                {
                    // 已经达到了最大条数，
                    //				PullToRefreshUtil.setLoadLabel(contentView, "已经达到了最大条数");
                    PullToRefreshUtil.setLoadLabel(contentView, "没有更多了");
                }
                else
                {
                    // 没有更多了， 所以不再加载下一页
                    PullToRefreshUtil.setLoadLabel(contentView, "没有更多了");
                }
            }
        }
        contentView.onRefreshComplete();
    }

    @Override
    public void dispose() {
        super.dispose();
    }

    @Override
    public int enter(IUIPage<?> arg0) {
        showGuide();
        if (NetworkUtil.isNetAvailable(bActivity))
        {
            setPageInfo();
            // clearPage();
            contentItemView.setFromType(pagetype);
            contentItemView.updateSwitchView(0);// 加载动画
            contentItemView.getInteractionData(0);// 初始装载
            rlayNoNetTopTip.setVisibility(View.GONE);
        }
        else
        {
            //			new NoNetDialog(bActivity).show();
            rlayNoNetTopTip.setVisibility(View.VISIBLE);
        }
        qryUnReadTotal();

        registerMsgUnreadInfoObserver(true);
        registerSystemMessageObservers(true);
        return 0;
    }

    private void qryUnReadTotal() {
        long lastQryTime = QyreaderPerferencesUtil.getInstance(bActivity, Const.phone_number).getLastQryTime();
        if (pagetype == 1) new QryUnReadActivityAction(bActivity, lastQryTime, new GetUnReadActivity()).start();
        new QryUnReadTotalAction(bActivity, DefaultConsts.TYPE_WRITESOURCE_ENTERPRISE, new GetUnreadAction(true)).start();
        new QryUnReadTotalAction(bActivity, DefaultConsts.TYPE_WRITESOURCE_SYSTEM, new GetUnreadAction(false)).start();
    }

    private Integer tempE = null, tempS = null;

    private class GetUnreadAction
            extends
            BaseAction
    {
        boolean flag;

        public GetUnreadAction(boolean flag) {
            this.flag = flag;
        }

        @Override
        public void OK(Object obj) {
            final int count = (Integer) obj;
            if (flag)
            {
                // if(count>0) Const.UNREAD_MSG_COUNT_E = count;
                tempE = count;
            }
            else
            {
                // if(count>0) Const.UNREAD_MSG_COUNT_S = count;
                tempS = count;
            }
            if (tempE != null && tempS != null)
            // if (Const.UNREAD_MSG_COUNT_E != null && Const.UNREAD_MSG_COUNT_S
            // != null)
            {
                bActivity.getUIHandler().post(new Runnable()
                {
                    @Override
                    public void run() {
                        boolean res = (tempE == 0 && tempS == 0) ? false : true;
                        // boolean res = (Const.UNREAD_MSG_COUNT_E == 0 &&
                        // Const.UNREAD_MSG_COUNT_S == 0) ? false : true;
                        ivMsgUnread.setVisibility(res ? View.VISIBLE : View.GONE);
                    }
                });
            }
        }
    }

    class GetUnReadActivity
            extends
            BaseAction
    {

        @Override
        public void OK(Object obj) {
            String hasNew = (String) obj;
            if (hasNew.equals("y"))
            {
                ivManagerRedDot.setVisibility(View.VISIBLE);
            }
            else
            {
                ivManagerRedDot.setVisibility(View.GONE);
            }

        }

    }

    private void onLeave() {
        registerMsgUnreadInfoObserver(false);

        registerSystemMessageObservers(false);

    }

    @Override
    public int leave(IUIPage<?> arg0) {
        onLeave();
        return 0;
    }

    @Override
    public void notifyView(int arg0, Bundle arg1) {
        switch (arg0) {
            case DefaultConsts.PAGE_ONRESUME_CODE:
                // contentItemView.getInteractionData(1);
                qryUnReadTotal();
//				long lastQryTime = QyreaderPerferencesUtil.getInstance(bActivity, Const.phone_number).getLastQryTime();
//				if (pagetype == 1) new QryUnReadActivityAction(bActivity, lastQryTime, new GetUnReadActivity()).start();
                break;
            case DefaultConsts.MESSAGE_UNREAD_CHANGE_CODE:
                boolean res = arg1.getBoolean("result");
                ivMsgUnread.setVisibility(res ? View.VISIBLE : View.GONE);
                break;
            case BaseBusinessActivity.COMMENTS_REQUEST_CODE:
                //互动中心评论发送成功
                //				Utils.showToast(bActivity, "互动中心评论成功");
                contentItemView.updateComment(arg1.getInt("position"), arg1.getInt("count"));
                break;
            case DefaultConsts.START_PUBLISH_THEME_ACTIVITY:
                contentItemView.getInteractionData(1);
                break;
        }
    }

    @Override
    public void setStatus(int arg0) {

    }

    @Override
    public View updateView(int arg0, ITaskResult arg1) {
        return null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.new_common_header_msg_layout:
                goMessagePage();
                break;
            case R.id.new_common_header_persion:// 跳转到显示联系人界面
                //				Intent intent = new Intent();
                //				intent.setClass(context, NewIntercationCenterToLinkmanActivity.class);
                //				context.startActivity(intent);
                bActivity.goPersonalActivity();
                break;
            case R.id.new_common_header_manager:
                new ManagerClickPopupWindow(context, new IManagerClickPopListener()
                {

                    @Override
                    public void ok(int i, ManagerClickPopupWindow pop) {
                        if (i == 0)
                        {
                            Intent actvListIntent = new Intent(bActivity, NewInteractionActvListActivity.class);
                            bActivity.startActivity(actvListIntent);
                            onLeave();

                        }
                        if (i == 1)
                        {
                            //Toast.makeText(context, "聊天列表", 0).show();
                            Intent intent = new Intent();
                            // intent.setClass(context, NewInteractionDetailsActivity.class);
                            intent.setClass(context, ContactMainActivity.class);
                            context.startActivity(intent);
                            onLeave();
                        }
                        pop.dismiss();
                    }
                }).showAsDropDown(ivManager, -ScreenUtil.dip2px(47), ScreenUtil.dip2px(-10));
                break;
            case R.id.new_common_header_setting:// 设置按钮
                bActivity.goPersonalActivity();
                break;
            case R.id.new_common_title_layout:
                titleDoubleClick();
                break;
            case R.id.new_interaction_center_postmsg:
                if (postmsgAnimation != null && postmsgAnimation.isRunning())
                {
                    postmsgAnimation.stop();
                }
                Intent postmsg = new Intent();
                postmsg.setClass(context, NewInteractionCenterUserPublishActivity.class);
                //				context.startActivity(postmsg);
                bActivity.startActivityForResult(postmsg, DefaultConsts.START_PUBLISH_THEME_ACTIVITY);
                break;
            case R.id.new_i_no_net_top_tip_rlay:
                startWirelessSettingsActivity(bActivity);
        }
    }

    /**
     * 跳转到网络设置页面
     *
     * @param context
     */

    private void startWirelessSettingsActivity(Activity context) {
        try
        {
            Intent intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
            intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            context.startActivity(intent);
        }
        catch (ActivityNotFoundException e)
        {

        }
    }

    private void goMessagePage() {
        bActivity.startActivity(new Intent(bActivity, MessageActivity.class));
    }

    private int       clickCount;
    private long      preClickTime;
    /** 双击有效时间500毫秒 */
    private final int defalultValue = 500;

    /** 标题栏双击，回到顶部 */
    private void titleDoubleClick() {
        if (clickCount == 0)
        {
            preClickTime = System.currentTimeMillis();
            clickCount++;
        }
        else if (clickCount == 1)
        {
            if ((System.currentTimeMillis() - preClickTime) < defalultValue)
            {
                gotoTop();
            }
            clickCount = 0;
            preClickTime = 0;
        }
        else
        {
            clickCount = 0;
            preClickTime = 0;
        }
    }

    /** 回到顶部 */
    private void gotoTop() {
        contentItemView.post(new Runnable()
        {
            @Override
            public void run() {
                contentView.getRefreshableView().scrollTo(0, 0);
            }
        });
    }

    private GuideDialog dialog;
    private boolean                 showHelp;
    private QyreaderPerferencesUtil util;
    private ImageView               postmsg;
    private Button                  ivNewMsg;

    private void initGuide() {
        util = QyreaderPerferencesUtil.getInstance(bActivity, DefaultConsts.FIRST_TAG);
        dialog = new GuideDialog(bActivity, R.layout.enterprise_page_firstin);
    }

    private void showGuide() {
        if (util == null || dialog == null)
        {
            initGuide();
        }
        showHelp = util.getShowEnterpriseHelp();
        if (showHelp)
        {
            if (null != dialog && !dialog.isShowing())
            {
                dialog.show();
            }
            util.setShowEnterpriseHelp(false);
        }
    }

    /**
     * 未读消息数量观察者
     */

    private void registerMsgUnreadInfoObserver(boolean register) {
        if (register)
        {
            ReminderManager.getInstance().registerUnreadNumChangedCallback(this);
        }
        else
        {
            ReminderManager.getInstance().unregisterUnreadNumChangedCallback(this);

        }
    }

    /**
     * 注册/注销新消息
     *
     * @param register
     */
    private void registerSystemMessageObservers(boolean register) {
        NIMClient.getService(MsgServiceObserve.class).observeReceiveMessage(incomingMessageObserver, true);
    }

    /**
     * 定义一个观察者
     */
    Observer<List<IMMessage>> incomingMessageObserver = new Observer<List<IMMessage>>()
    {
        @Override
        public void onEvent(List<IMMessage> messages) {
            updateRedDot(true);
        }
    };

    @Override
    public void onUnreadNumChanged(ReminderItem item) {
        boolean b;
        if (item != null && item.getUnread() > 0)
        {
            b = true;
        }
        else
        {
            b = false;
        }
        updateRedDot(b);
    }

    /**
     * 刷新小红点的状态
     *
     * @param b
     */

    private void updateRedDot(final boolean b) {
        if (pagetype == 1)
        {
            bActivity.getUIHandler().post(new Runnable()
            {

                @Override
                public void run() {
                    ivManagerRedDot.setVisibility(b ? View.VISIBLE : View.GONE);

                }
            });
        }
        else if (pagetype == 2)
        {
            bActivity.getUIHandler().post(new Runnable()
            {

                @Override
                public void run() {
                    ivPersionRedDot.setVisibility(b ? View.VISIBLE : View.GONE);
                }
            });
        }
    }

}
